<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <!--            <el-form-item label="项目" prop="projectName">-->
            <!--                <el-input-->
            <!--                        v-model="queryParams.projectName"-->
            <!--                        placeholder="请输入项目名称"-->
            <!--                        clearable-->
            <!--                        @keyup.enter.native="handleQuery"-->
            <!--                />-->
            <!--            </el-form-item>-->
            <el-form-item label="网关编号" prop="gatewayNumber">
                <el-input
                    v-model="queryParams.gatewayNumber"
                    placeholder="请输入网关编号"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>

            <el-form-item label="卡号" prop="flowCardNumber">
                <el-input
                    v-model="queryParams.flowCardNumber"
                    placeholder="请输入流量卡卡号"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="经销商" prop="companyId">
                <el-select v-model="queryParams.companyId" placeholder="请选择经销商" filterable clearable
                           @change="getList"
                >
                    <el-option
                        v-for="item in companyList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    ></el-option>
                </el-select>
            </el-form-item>
            <!--      <el-form-item label="流量总额" prop="flowTotal">-->
            <!--        <el-input-->
            <!--          v-model="queryParams.flowTotal"-->
            <!--          placeholder="请输入流量总额"-->
            <!--          clearable-->
            <!--          size="small"-->
            <!--          @keyup.enter.native="handleQuery"-->
            <!--        />-->
            <!--      </el-form-item>-->
            <!--      <el-form-item label="剩余流量" prop="flowBalance">-->
            <!--        <el-input-->
            <!--          v-model="queryParams.flowBalance"-->
            <!--          placeholder="请输入剩余流量"-->
            <!--          clearable-->
            <!--          size="small"-->
            <!--          @keyup.enter.native="handleQuery"-->
            <!--        />-->
            <!--      </el-form-item>-->
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                    v-hasPermi="['business:gatewayInfo:add']"
                >新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="success"
                    plain
                    icon="el-icon-edit"
                    size="mini"
                    :disabled="single"
                    @click="handleUpdate"
                    v-hasPermi="['business:gatewayInfo:edit']"
                >修改
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="danger"
                    plain
                    icon="el-icon-delete"
                    size="mini"
                    :disabled="multiple"
                    @click="handleDelete"
                    v-hasPermi="['business:gatewayInfo:remove']"
                >删除
                </el-button>
            </el-col>

            <el-col :span="1.5">
                <el-button
                    plain
                    size="mini"
                    :disabled="multiple"
                    @click="handleUpdateExpire"
                >批量修改有效期
                </el-button>
            </el-col>
            <!--      <el-col :span="1.5">-->
            <!--        <el-button-->
            <!--          plain-->
            <!--          size="mini"-->
            <!--          :disabled="single"-->
            <!--          @click="handleFlowCard"-->
            <!--          v-hasPermi="['business:gatewayInfo:edit']"-->
            <!--        >流量卡信息-->
            <!--        </el-button>-->
            <!--      </el-col>-->

            <el-col :span="1.5">
                <el-button
                    type="warning"
                    plain
                    icon="el-icon-download"
                    size="mini"
                    @click="handleExport"
                >导出
                </el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <!--  :cell-style="bgColor"   -->
        <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">

            <el-table-column type="expand">
                <template slot-scope="props">

                    <el-descriptions class="margin-top" :column="2" border>
                        <el-descriptions-item>
                            <template slot="label">
                                流量卡卡号
                            </template>
                            {{ props.row.flowCardNumber }}
                        </el-descriptions-item>
                        <el-descriptions-item>
                            <template slot="label">
                                流量卡有效期
                            </template>
                            {{ parseTime(props.row.effectiveTime, '{y}-{m}-{d}') }}
                        </el-descriptions-item>
                        <el-descriptions-item>
                            <template slot="label">
                                流量总额
                            </template>
                            {{ props.row.flowTotal }}
                        </el-descriptions-item>
                        <el-descriptions-item>
                            <template slot="label">
                                剩余流量
                            </template>
                            {{ props.row.flowBalance }}
                        </el-descriptions-item>

                    </el-descriptions>

                </template>
            </el-table-column>

            <el-table-column type="selection" width="55" align="center"/>

            <!--      <el-table-column label="主键" align="center" prop="gatewayInfoId" width="50" />-->
            <!--            <el-table-column label="序号" align="center" type="index" :index="calculateIndex"/>-->

            <el-table-column label="网关编号" align="center" prop="gatewayNumber" width="180"/>

            <el-table-column label="项目" align="center" prop="projectName"/>

            <el-table-column label="流量卡" align="center" prop="flowCardNumber">
                <template slot-scope="scope">
                    <el-link @click="handleFlowCard(scope.row)" type="primary" v-if="scope.row.flowCardNumber !== null"
                             :underline="false"
                    >已绑定
                    </el-link>
                    <el-link @click="handleFlowCard(scope.row)" type="info" v-if="scope.row.flowCardNumber === null"
                             :underline="false"
                    >未绑定
                    </el-link>
                </template>
            </el-table-column>

            <el-table-column label="状态" align="center" prop="status">
                <template slot-scope="scope">
                    <el-link v-if="scope.row.status" type="primary" :underline="false">启用</el-link>
                    <el-link v-else type="info" :underline="false">禁用</el-link>
                </template>
            </el-table-column>

            <el-table-column label="有效期" align="center" prop="expireTime">
                <template v-slot="scope">
                    <span>{{ parseTime(scope.row.expireTime) }}</span>
                </template>
            </el-table-column>

            <el-table-column label="添加人" align="center" prop="createBy"/>

            <el-table-column label="添加日期" align="center" prop="createTime">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>


            <!--   网关启用日期，换一个字段存储这个值，换到   -->
            <!--      <el-table-column label="项目启用日期" align="center" prop="beginPayTime" width="100">-->
            <!--        <template slot-scope="scope">-->
            <!--          <span>{{ parseTime(scope.row.beginPayTime, '{y}-{m}-{d}') }}</span>-->
            <!--        </template>-->
            <!--      </el-table-column>-->


            <!--      <el-table-column label="天数" align="center">-->
            <!--        <template slot-scope="scope">-->
            <!--          <span v-if="scope.row.flowCardId !== null">{{ compareDate(scope.row.effectiveTime) }}</span>-->
            <!--        </template>-->
            <!--      </el-table-column>-->

            <!--      <el-table-column label="备注" align="center" prop="remark" />-->
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">

                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleUpdate(scope.row)"
                        v-hasPermi="['business:info:edit']"
                    >修改
                    </el-button>

                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="handleDelete(scope.row)"
                        v-hasPermi="['business:info:remove']"
                    >删除
                    </el-button>

                    <el-button
                        size="mini"
                        type="text"
                        @click="handlePay(scope.row)"
                    >充值
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 添加或修改网关基本信息对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="60px" size="small">

                <el-form-item label="编号" prop="gatewayNumber">
                    <el-input v-model="form.gatewayNumber" placeholder="请输入网关编号"/>
                </el-form-item>

                <el-form-item label="型号" prop="gatewayModel">
                    <el-select v-model="form.gatewayModel"
                               placeholder="请选择网关型号"
                    >
                        <el-option
                            v-for="item in gatewayModelList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="有效期" prop="expireTime">
                    <el-date-picker
                        v-model="form.expireTime"
                        value-format="timestamp"
                        type="datetime"
                        placeholder="有效期"
                    >
                    </el-date-picker>
                </el-form-item>

                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="form.status" size="small">
                        <el-radio-button :label="true">启用</el-radio-button>
                        <el-radio-button :label="false">禁用</el-radio-button>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
                </el-form-item>

            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button size="small" type="primary" @click="submitForm">{{ buttonText }}</el-button>
                <el-button size="small" @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 流量卡 -->
        <el-dialog title="流量卡" :visible.sync="flowCardOpen" width="500px" append-to-body>
            <FlowCard :row="flowCardForm" :key="flowCardFormKey"/>
        </el-dialog>

        <el-dialog title="充值网关" :visible.sync="payGatewayOpen" width="500px" append-to-body>
            <el-form ref="form" :model="payForm">
                <el-form-item label="网关编号">
                    <el-input readonly v-model="payForm.gatewayNumber"/>
                </el-form-item>
                <el-form-item label="套餐" prop="productId">
                    <el-select v-model="payForm.productId"
                               placeholder="请选择套餐"
                               @change="changeProduct"
                    >
                        <el-option
                            v-for="item in gatewayPackageList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="套餐价格(元)">
                    <el-input readonly v-model="productInfo.price"/>
                </el-form-item>
                <el-form-item label="套餐天数">
                    <el-input readonly v-model="productInfo.dayNum"/>
                </el-form-item>
                <el-form-item>
                    <el-button type="success" @click="submitProduct">充值</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <el-dialog title="批量修改有效期" :visible.sync="batchUpdateExpireOpen" width="400px" append-to-body>
            <el-form ref="form" :model="batchUpdateExpireForm">
                <el-tabs v-model="batchUpdateExpireForm.type" @tab-click="changeTabs">
                    <el-tab-pane label="指定时间" :name="0">
                        <el-form-item label="有效期">
                            <el-date-picker
                                v-model="batchUpdateExpireForm.expireTime"
                                value-format="timestamp"
                                type="datetime"
                                placeholder="有效期"
                            >
                            </el-date-picker>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="固定天数" :name="1">
                        <el-form-item label="固定天数">
                            <el-input  v-model="batchUpdateExpireForm.num"/>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="固定年数" :name="2">
                        <el-select v-model="batchUpdateExpireForm.num"
                                   placeholder="请选择年"
                                   style="margin-bottom: 10px"
                        >
                            <el-option
                                v-for="item in yearsList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-tab-pane>
                </el-tabs>

                <el-form-item>
                    <el-button type="success" @click="batchUpdateExpireFormSubmit">提交</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

    </div>
</template>

<script>
import {
    addGatewayInfo,
    delGatewayInfo,
    getGatewayInfo,
    listGatewayInfo,
    batchUpdateExpire,
    pay,
    updateGatewayInfo
} from '@/api/backstage/gatewayInfo'
import { listGatewayModelChoose } from '@/api/business/gatewayModel'
import { listGatewayPackageSelect, getGatewayPackage } from '@/api/backstage/gatewayPackage'
import { companySelect } from '@/api/business/company'
import FlowCard from './flowCard'

export default {
    name: 'Info',
    components: {
        FlowCard
    },
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 网关基本信息表格数据
            infoList: [],
            // 弹出层标题
            title: '',
            buttonText: '',
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                gatewayNumber: null,
                companyId: null,
                effectiveTime: null,
                lastPayTime: null,
                beginPayTime: null,
                endPayTime: null,
                flowCardNumber: null,
                flowTotal: null,
                flowBalance: null
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                gatewayNumber: [
                    { required: true, trigger: 'blur', message: '请输入网关编号' }
                ],
                gatewayModel: [
                    { required: true, trigger: 'blur', message: '请选择网关型号' }
                ]
            },

            flowCardOpen: false,
            flowCardForm: {},
            flowCardFormKey: 0,

            gatewayModelList: [],

            payGatewayOpen: false,
            payForm: {},
            gatewayPackageList: [],
            productInfo: {},

            batchUpdateExpireOpen: false,
            batchUpdateExpireForm: {
                ids: [],
                expireTime: null,
                type: 0,
                num: null
            },
            // 经销商列表
            companyList: [],
            // 天数
            yearsList: [
                { value: 1, label: '1年' },
                { value: 2, label: '2年' }
            ]
        }
    },
    created() {
        this.getList()
        this.getGatewayModelList()
        this.getGatewayPackageSelect()
        this.getCompanySelect()
    },
    // mounted() { //添加监听滚动条事件
    //   window.addEventListener('scroll', this.handleScroll, true)
    // },
    // destroyed() { //移除（跳转页面后移除）
    //   window.removeEventListener('scroll', this.handleScroll, true)
    // },
    methods: {
        changeTabs(){
          this.batchUpdateExpireForm.expireTime= null
          this.batchUpdateExpireForm.num=null
        },
        // 获取进销商
        getCompanySelect() {
            companySelect().then(res => {
                this.companyList = res.data
            })
        },

        getGatewayPackageSelect() {
            listGatewayPackageSelect().then(response => {
                this.gatewayPackageList = response.data
            })
        },

        changeProduct(productId) {
            getGatewayPackage(productId).then(response => {
                this.productInfo = response.data
            })
        },

        bgColor({ row, column, rowIndex, columnIndex }) {
            if (this.compareDate(row.effectiveTime) === '1' && columnIndex === 10) {
                return {
                    color: '#CCC'
                }
            }

            if (this.compareDate(row.effectiveTime) === '2' && columnIndex === 10) {
                return {
                    color: '#FF0000'
                }
            }
        },
        // 比较日期大小
        compareDate(effectiveTime) {

            let endDate = new Date(Date.parse(effectiveTime.replace(/-/g, '/')))

            let date = new Date()
            let year = date.getFullYear()
            let month = date.getMonth() + 1
            let day = date.getDate()
            let current = year + '-' + month + '-' + day

            console.log('流量卡过期时间，', endDate)

            let currentDate = new Date(Date.parse(current.replace(/-/g, '/')))
            if (currentDate > endDate) {
                //console.log("有效期：" + endTime, "当前日期：" + current)
                //console.log("过期了")
                return '1'
            }

            // 当前时间加上30天
            let ready = this.calculateDate(currentDate, 30)

            //console.log("加之后：" + ready)
            let readyDate = new Date(Date.parse(ready.replace(/-/g, '/')))

            console.log('加了30天之后：', readyDate)

            // 加了30天后再比较
            if (readyDate > endDate) {
                console.log(readyDate)
                return '2'
            }

        },

        calculateDate(date, days) {
            if (days === undefined || days === '') {
                days = 1
            }
            let newDate = new Date(date)
            // console.log("加之前：" + date)
            newDate.setDate(newDate.getDate() + days)
            let month = newDate.getMonth() + 1
            let day = newDate.getDate()
            return newDate.getFullYear() + '-' + month + '-' + day
        },

        calculateIndex(index) {
            const pageNum = this.queryParams.pageNum
            const pageSize = this.queryParams.pageSize
            return index + 1 + (pageNum - 1) * pageSize
        },
        /** 查询网关基本信息列表 */
        getList() {
            this.loading = true
            listGatewayInfo(this.queryParams).then(response => {
                this.infoList = response.rows
                this.total = response.total
                this.loading = false
            })
        },
        // 取消按钮
        cancel() {
            this.open = false
            // 流量卡弹出框关闭
            this.flowCardOpen = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                gatewayInfoId: null,
                gatewayNumber: null,
                effectiveTime: null,
                lastPayTime: null,
                beginPayTime: null,
                endPayTime: null,
                flowCardType: null,
                flowCardNumber: null,
                flowTotal: null,
                flowBalance: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                remark: null
            }
            this.resetForm('form')
        },

        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.gatewayInfoId)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset()
            this.open = true
            this.title = '添加网关基本信息'
            this.buttonText = '添 加'
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset()
            const gatewayInfoId = row.gatewayInfoId || this.ids
            getGatewayInfo(gatewayInfoId).then(response => {
                this.form = response.data
                this.open = true
                this.title = '修改网关基本信息'
                this.buttonText = '修 改'
            })
        },

        /** 流量卡信息 */
        handleFlowCard(row) {
            this.flowCardForm = row
            this.flowCardFormKey += 1
            this.flowCardOpen = true
        },

        /** 提交按钮 */
        submitForm() {
            this.$refs['form'].validate(valid => {
                if (valid) {
                    if (this.form.gatewayInfoId != null) {
                        updateGatewayInfo(this.form).then(response => {
                            this.$modal.msgSuccess('修改成功')
                            this.open = false
                            this.getList()
                        })
                    } else {
                        addGatewayInfo(this.form).then(response => {
                            this.$modal.msgSuccess('新增成功')
                            this.open = false
                            this.getList()
                        })
                    }
                }
            })
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const gatewayInfoIds = row.gatewayInfoId || this.ids
            this.$modal.confirm('是否确认删除网关基本信息编号为"' + gatewayInfoIds + '"的数据项？').then(function() {
                return delGatewayInfo(gatewayInfoIds)
            }).then(() => {
                this.getList()
                this.$modal.msgSuccess('删除成功')
            }).catch(() => {
            })
        },

        handleUpdateExpire(row) {
            this.batchUpdateExpireOpen = true
        },

        batchUpdateExpireFormSubmit() {
            console.log('batchUpdateExpireFormSubmit', this.batchUpdateExpireForm)
            this.batchUpdateExpireForm.ids = this.ids
            if (this.batchUpdateExpireForm.type === 0) {
                this.batchUpdateExpireForm.num = null
            }
            if (this.batchUpdateExpireForm.type === 1 || this.batchUpdateExpireForm.type === 2) {
                this.batchUpdateExpireForm.expireTime = null
            }
            batchUpdateExpire(this.batchUpdateExpireForm).then(response => {
                this.$message.success('修改成功')
                this.batchUpdateExpireOpen = false
                this.getList()
            })
        },

        handlePay(row) {
            this.payForm.gatewayNumber = row.gatewayNumber
            this.payGatewayOpen = true
        },

        submitProduct() {
            pay(this.payForm).then(response => {
                this.$message.success('充值成功')
                this.payGatewayOpen = false
                this.getList()
            })
        },

        /** 导出按钮操作 */
        handleExport() {
            let obj = {
                flowCardNumber: this.queryParams.flowCardNumber,
                gatewayNumber: this.queryParams.gatewayNumber,
                companyId: this.queryParams.companyId
            }
            this.download('business/gatewayInfo/export', {
                ...obj
            }, `网关有效期_${new Date().getTime()}.xlsx`)
        },

        getGatewayModelList() {
            listGatewayModelChoose().then(response => {
                this.gatewayModelList = response.data
            }, error => {
            })
        }
    }
}
</script>
